package com.cqupt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cqupt.service.ItemService;
import com.cqupt.utils.APIUtils;
import com.cqupt.utils.DateUtils;
import com.cqupt.utils.TextUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ItemServiceImpl implements ItemService {
    /**
* @Description //启用监控项
* @Date 22:15 2020/11/29
* @Param [token, itemId]
**/
    @Override
    public boolean enableMontiorItem(String itemid) {
        String token = APIUtils.getToken();
        /**
         * 参数组装
         */
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "item.update");
            put("id", 1);
            put("params",new HashMap<String,Object>(){{
                put("itemid",itemid);
                put("status",0);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        /**
         * 获取结果
         */
        Map<String,List<String>> resultMap = (Map<String,List<String>>)responseMap.get("result");
        List<String>  receiveItemid = resultMap.get("itemids");
        if (itemid.equals(receiveItemid.get(0)))
            return true;
        else
            return false;
    }
/**
* @Description //停用监控项
* @Date 22:16 2020/11/29
* @Param [token, itemId]
**/
    @Override
    public boolean stopMontiorItem(String itemid) {
        String token = APIUtils.getToken();
        /**
         * 参数组装
         */
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "item.update");
            put("id", 1);
            put("params",new HashMap<String,Object>(){{
                put("itemid",itemid);
                put("status",1);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        Map<String,List<String>> itemsidResult = (Map<String,List<String>>)responseMap.get("result");
        List<String> resultItemids = itemsidResult.get("itemids");
        if (itemid.equals(resultItemids.get(0)))
            return true;
        else
            return false;
    }
/**
* @Description //删除监控项
* @Date 22:16 2020/11/29
* @Param [token, itemList]
**/
    @Override
    public Map<String, Object> deleteMonitorItem(List<String> itemList) {
        Map<String, Object> resMap = new HashMap<>();
        String token = APIUtils.getToken();
        /**
         * 参数组装
         */
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "item.delete");
            put("id", 1);
            put("params",itemList);
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        Object result = responseMap.get("result");
        if(result != null){
            resMap.put("flag",true);
            resMap.put("message","");
            return resMap;
        }
        else{
            Map<String,Object> error = (Map<String, Object>) responseMap.get("error");
            String message = error.get("data").toString();
            HashMap<String, Object> returnMap = new HashMap<>();
            returnMap.put("flag",false);
            returnMap.put("message",message);
            return returnMap;
        }
    }
/**
* @Description //获取指定主机的所有监控项的相关值
* @Date 22:18 2020/11/29
* @Param [token, ]hostId
**/
    @Override
    public List<Map<String, Object>> getAllItem(String hostId) {
        //目标汉化字段
        Map<String, String> initHostItem = TextUtils.getDataToMap();
        String token = APIUtils.getToken();
        List<String> itemList = new ArrayList<>();
        itemList.add("delay");
        itemList.add("key_");
        itemList.add("name");
        itemList.add("type");
        itemList.add("value_type");
        itemList.add("history");
        itemList.add("status");
        itemList.add("trends");
        /**
         * 参数组装
         */
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("params",new HashMap<String,Object>(){{
                put("output",itemList);
                put("hostids",hostId);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String,Object>> resultList = (List<Map<String,Object>>)responseMap.get("result");
//        System.out.println(resultList);
        //对数据进行翻译封装
        List<Map<String, Object>> itemNewsList = changTypeString(resultList);
        for (int i = 0; i < itemNewsList.size(); i++) {
            TextUtils.replaceString(itemNewsList.get(i),"Zabbix","device","name");
            Map<String, Object> stringObjectMap = itemNewsList.get(i);
            String name = (String) stringObjectMap.get("name");
            stringObjectMap.put("name", initHostItem.get(name)==null?name:initHostItem.get(name));
        }
        return itemNewsList;
    }
/**
* @Description //创建监控项
* @Date 16:35 2020/11/30
* @Param [allNewsForItem]
**/
    @Override
    public Map<String,Object> creatMonitorItem(Map<String,Object> allNewsForItem,int type) {
        String token = APIUtils.getToken();
        Map<String,Object> paramsMap = null;
        //agent类型监控项
        if (type == 0){
            /**
             * 参数组装
             */
            paramsMap = new HashMap<String,Object>(){{
                put("auth",token);
                put("jsonrpc", "2.0");
                put("method", "item.create");
                put("id", 1);
                put("params",new HashMap<String,Object>(){{
                    put("delay",allNewsForItem.get("delay"));
                    put("hostid",allNewsForItem.get("hostid"));
                    put("interfaceid",allNewsForItem.get("interfaceid"));
                    put("key_",allNewsForItem.get("key_"));
                    put("name",allNewsForItem.get("name"));
                    put("type",allNewsForItem.get("type"));
                    put("value_type",allNewsForItem.get("value_type"));
                    put("description",allNewsForItem.get("description"));
                    put("history",allNewsForItem.get("history"));
                    put("trends",allNewsForItem.get("trends"));
                }});
            }};
        }
        //SNMP类型监控项
        else if(type == 1){
            /**
             * 参数组装
             */
            paramsMap = new HashMap<String,Object>(){{
                put("auth",token);
                put("jsonrpc", "2.0");
                put("method", "item.create");
                put("id", 1);
                put("params",new HashMap<String,Object>(){{
                    put("delay",allNewsForItem.get("delay"));
                    put("hostid",allNewsForItem.get("hostid"));
                    put("interfaceid",allNewsForItem.get("interfaceid"));
                    put("key_",allNewsForItem.get("key_"));
                    put("snmp_oid",allNewsForItem.get("snmp_oid"));
                    put("name",allNewsForItem.get("name"));
                    //put("type",allNewsForItem.get("type"));
                    put("type",20);
                    put("value_type",allNewsForItem.get("value_type"));
                    put("description",allNewsForItem.get("description"));
                    put("history",allNewsForItem.get("history"));
                    put("trends",allNewsForItem.get("trends"));
                }});
            }};
        }
        else if (type == 7){
            /**
             * 参数组装
             */
            paramsMap = new HashMap<String,Object>(){{
                put("auth",token);
                put("jsonrpc", "2.0");
                put("method", "item.create");
                put("id", 1);
                put("params",new HashMap<String,Object>(){{
                    put("delay",allNewsForItem.get("delay"));
                    put("hostid",allNewsForItem.get("hostid"));
                    put("interfaceid",allNewsForItem.get("interfaceid"));
                    put("key_",allNewsForItem.get("key_"));
                    put("name",allNewsForItem.get("name"));
                    put("type",allNewsForItem.get("type"));
                    put("value_type",allNewsForItem.get("value_type"));
                    put("description",allNewsForItem.get("description"));
                    put("history",allNewsForItem.get("history"));
                    put("trends",allNewsForItem.get("trends"));
                }});
            }};
        }
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        /**
         * 获取请求结果
         */
        Map<String,Object> result = (Map<String, Object>) responseMap.get("result");
        Map<String, Object> returnMap = new HashMap<>();
        if(result != null){
            String itemids = ((List<String>)result.get("itemids")).get(0);
            returnMap.put("flag",true);
            returnMap.put("message",itemids);
        }else {
            Map<String,Object> error = (Map<String, Object>) responseMap.get("error");
            String message = error.get("data").toString();
            returnMap.put("flag",false);
            returnMap.put("message",message);
        }
        return returnMap;
    }

    /**
     * 从xml文件中读取键值
     * @return
     */
    @Override
    public Map<String,List<Map<String, Object>>> getItemKeyFromXml() {
        SAXReader sr=new SAXReader();
        //(2)加载需要解析文件
        String path = ItemServiceImpl.class.getClassLoader().getResource("itemKeyList.xml").getPath();
        File file=new File(path);
        Document dou= null;
        try {
            dou = sr.read(file);
            //(3)获取根标签元素
            Element root=dou.getRootElement();
            //(4)根据需求去解析想要的数据,对dom树的迭代过程
            Iterator<Element> iterator = root.elementIterator();
            Map<String,List<Map<String, Object>>> keyMap = new HashMap<String, List<Map<String, Object>>>();
            while (iterator.hasNext()){
                Element e = iterator.next();
                Attribute attribute = e.attribute("name");
                if (attribute.getValue().equals("agent")){
                    List<Map<String, Object>> itemKeyList = defineXMLMap(e);
                    keyMap.put("agent",itemKeyList);
                }
                if (attribute.getValue().equals("activite")){
                    List<Map<String, Object>> itemKeyList = defineXMLMap(e);
                    keyMap.put("activite",itemKeyList);
                }
                if (attribute.getValue().equals("SNMP trap")){
                    List<Map<String, Object>> itemKeyList = defineXMLMap(e);
                    keyMap.put("SNMP_trap",itemKeyList);
                }
            }
            return keyMap;
        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        }
    }
/**
* @Description //创建主机类型时初始化监控项
* @Date 15:08 2020/12/25
* @Param [hostid, interfaceid]
**/
    @Override
    public Map<String, Object> createItemInitHost(String hostid, String interfaceid) {
        String token = APIUtils.getToken();
        //主机类型监控项键值
        Map<String, String> initHostItem = new HashMap<String, String>() {{
            put("CPU负载","system.cpu.load[<cpu>,<mode>]");
            put("内存占用","vm.memory.size[<mode>]");
            put("磁盘空间剩余","vfs.fs.size[fs,<mode>]");
            put("系统级日志","log[file,<regexp>,<encoding>,<maxlines>,<mode>,<output>,<maxdelay>,<options>]");
        }};
            List<Map<String, Object>> initItemParams = new ArrayList<>();
            Set<Map.Entry<String, String>> entries = initHostItem.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                /**
                 * 参数组装
                 */
                Map<String, Object> initItemMap = new HashMap<>();
                String key = entry.getKey();
                String value = entry.getValue();
                initItemMap.put("delay", "30s");
                initItemMap.put("hostid", hostid);
                initItemMap.put("interfaceid", interfaceid);
                initItemMap.put("key_", value);
                initItemMap.put("name", key);
                initItemMap.put("type", 0);
                initItemMap.put("description", "");
                if ("系统级日志".equals(key))
                    initItemMap.put("value_type", 2);//判断数据类型
                else
                    initItemMap.put("value_type", 0);
                initItemParams.add(initItemMap);
            }
//        System.out.println(initItemParams);
        /**
         * 参数组装
         */
        Map<String,Object> paramsMap = new HashMap<String,Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "item.create");
            put("id", 1);
            put("params",initItemParams);
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        /**
         * 获取请求结果
         */
        Map<String,Object> result = (Map<String, Object>) responseMap.get("result");
        if (result != null)
            return result;
        return responseMap;
    }

    /**
    * @Description /封装xml文件的数据
    * @Date 15:17 2020/12/8
    * @Param
    **/
    private List<Map<String,Object>> defineXMLMap(Element e){
        List<Element> item = e.elements("item");
        List<Map<String, Object>> itemKeyList = new ArrayList<>();
        for (Element element : item){
            List<Element> elements = element.elements();
            Map<String, Object> itemKeyMap = new TreeMap<>();
            List<String> exps = new ArrayList<>();
            /**
             * 参数组装
             */
            Map<String, String> params = new HashMap<>();
            for (Element node: elements) {
                switch (node.getName()) {
                    case "example":
                        exps.add(node.getText());
                        break;
                    case "key":
                        itemKeyMap.put("key_", node.getText());
                        break;
                    case "value":
                        itemKeyMap.put("describe", node.getText());
                        break;
                    default:
                        params.put(node.getName(), node.getText());
                        break;
                }
            }
            itemKeyMap.put("examples", exps);
            itemKeyMap.put("params", params);
            itemKeyList.add(itemKeyMap);
        }
        return itemKeyList;
    }
    /**
    * @Description //修改监控项字段type、status的返回值
    * @Date 17:14 2020/12/2
    * @Param
    **/
    private List<Map<String,Object>> changTypeString(List<Map<String,Object>> resultList){
        for (int i = 0; i < resultList.size(); i++) {
            String type = (String) resultList.get(i).get("type");
            String status = (String) resultList.get(i).get("status");
            String value_type = resultList.get(i).get("value_type").toString();
            if(status.equals("0")){
                resultList.get(i).put("status","已启用");
            }else{
                resultList.get(i).put("status","未启用");
            }
            /**
             * 固定监控项字段的返回值
             */
            String[] valueTypeList = new String[]{"浮点数","字符","日志","数字(无正负)","文本"};
            String[] typeList = new String[]
                        {   "客户端",
                            "SNMPv1代理",
                            "设备采集器",
                            "简单检查",
                            "SNMPv2代理",
                            "设备内部",
                            "SNMPv3代理",
                            "客户端（主动式）",
                            "设备整合",
                            "网络监控",
                            "外部检查",
                            "数据库监控",
                            "IPMI客户端",
                            "SSH客户端",
                            "TELNET客户端",
                            "可计算的",
                            "JMX agent代理程序",
                            " SNMP trap",
                            "相关项目",
                            "HTTP代理",
                            "其他类型"};
            resultList.get(i).put("value_type",valueTypeList[Integer.parseInt(value_type)]);
            resultList.get(i).put("type",typeList[Integer.parseInt(type)]);
        }
        return resultList;
    }
/**
* @Description //创建SNMP类型时初始化监控项
* @Date 14:26 2020/12/27
* @Param [hostid, interfaceid]
**/
    @Override
    public Map<String, Object> createItemInitHostSNMP(String hostid, String interfaceid) {
        String token = APIUtils.getToken();
        //交换机、防火墙、单项网闸等SNMP设备监控项键值
        Map<String,String> initSNMPItem = new HashMap<String,String>(){{
            put("负载信息","system.cpu.load[<cpu>,<mode>]");//CPU 负载。返回浮点数
            put("硬件信息","sensor[device,sensor,<mode>]");//硬件传感器读数。返回浮点型
            put("端口状态","net.tcp.listen[port]");//检查 TCP 端口 是否处于侦听状态。返回 0 - 未侦听；1 - 正在侦听
            put("网络流量","net.if.total[if,<mode>]");//网络接口上传下载的流量总和。返回整数
            put("端口错包率","net.if.total[if,<errors>]");//
            put("端口丢包率","net.if.total[if,<dropped >]");//
            //put("端口带宽","");//
        }};
        List<Map<String, Object>> initItemParams = new ArrayList<>();
        Set<Map.Entry<String, String>> entries = initSNMPItem.entrySet();
        /**
         * 参数组装
         */
        for (Map.Entry<String, String> entry : entries) {
            Map<String, Object> initItemMap = new HashMap<>();
            String key = entry.getKey();
            String value = entry.getValue();
            initItemMap.put("delay", "30s");
            initItemMap.put("hostid", hostid);
            initItemMap.put("interfaceid", interfaceid);
            initItemMap.put("key_", value);
            initItemMap.put("name", key);
            initItemMap.put("snmp_oid","ifInUcastPkts");
            initItemMap.put("type", 4);
            initItemMap.put("description", "");
            if ("硬件信息" == key || "网络流量" == key)
                initItemMap.put("value_type", 0);//判断数据类型
            else
                initItemMap.put("value_type", 3);
            initItemParams.add(initItemMap);
        }
        System.out.println(initItemParams);
        Map<String,Object> paramsMap = new HashMap<String,Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "item.create");
            put("id", 1);
            put("params",initItemParams);
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        Map<String,Object> result = (Map<String, Object>) responseMap.get("result");
        if (result != null){
            return result;
        }

        return responseMap;
    }
/**
* @Description //汉化部分关键监控项
* @Date 18:39 2020/12/30
* @Param []
**/
    @Override
    public void translateItemName() {
        String token = APIUtils.getToken();
        //目标汉化字段
        Map<String, String> initHostItem = new HashMap<String, String>() {{
            put("CPU利用率","CPU utilization");
            put("内存利用率","Memory utilization");
            put("磁盘空间剩余","Available memory");
            put("CPU个数","Number of CPUs");
            put("进程个数","Number of processes");
        }};
        //查询模板所有监控项
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("params",new HashMap<String,Object>(){{
                put("output","extend");
                put("templateids","10001");
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String,Object>> resultList = (List<Map<String,Object>>)responseMap.get("result");
        for (int i = 0; i < resultList.size(); i++) {
            String name = resultList.get(i).get("name").toString();
            Set<Map.Entry<String, String>> entries = initHostItem.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                String value = entry.getValue();
                String key = entry.getKey();
                if (value.equals(name)){
                    resultList.get(i).put("name",key);
                }
            }
        }
    }

    //批量停用监控项
    public Map<String, Object> stopMontiorItems(List<String> itemLists) {
        String token = APIUtils.getToken();
        /**
         * 参数组装
         */
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "item.update");
            put("id", 1);
            List<Map<String, Object>> itemList = new ArrayList<Map<String, Object>>();
            for (int i = 0; i < itemLists.size(); i++){
                Map<String, Object> items = new HashMap<String, Object>();
                items.put("itemid", itemLists.get(i));
                items.put("status", 1);
                itemList.add(items);
            }
            put("params", itemList);
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        /**
         * 获取并返回请求结果
         */
        return (Map<String, Object>)responseMap.get("result");
    }

    // 初始化：创建固定的监控项至模板
    /**
        * @Description 参数：模板id、监控项名称name、监控项键值key
        * @date 2021/5/29 16:23
    */
    public Map<String, Object> createItemToTemplate(String templatesid,String key,String name){
        String token = APIUtils.getToken();
        // 创建磁盘监控项
        Map<String, Object> writeItemMap = new HashMap<String, Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "item.create");
            put("id", 1);
            put("params", new HashMap<String,Object>(){{
                put("hostid",templatesid);
                put("delay","1m");
                put("key_",key);
                put("name",name);
                put("type",0);
                put("value_type",0);
                put("description","");
                put("history","90d");
                put("trends","365d");
            }});
        }};
        return APIUtils.sendRequest(JSON.toJSONString(writeItemMap, SerializerFeature.WriteMapNullValue));
    }

//    删除模板自定义的监控项
    @Override
    public Map<String, Object> deleteItemToTemplate(String templatesid, String key, String name) {
        return null;
    }

    // 根据主机id获取关键监控项
    public List<Map<String,Object>> get_important_item_byid(String hostId, String token) {
        List<String> itemList = new ArrayList<>();
        // 键值
        itemList.add("key_");
        // 名称
        itemList.add("name");
        // 当前最后一次监控值
        itemList.add("lastvalue");
        // 最后监控时间
        itemList.add("lastclock");
        // 需要的键值列表
        List<String> key_val = new ArrayList<>();
        // 内存利用率
        key_val.add("vm.memory.utilization");
        // cpu利用率
        key_val.add("system.cpu.util");
        // 磁盘读
        key_val.add("vfs.dev.write");
        // 磁盘写
        key_val.add("vfs.dev.read");
        // 程序计数器windows
        key_val.add("perf_counter[\\\\2\\\\18]");
        // 程序计数器windows
        key_val.add("perf_counter[\\\\2\\\\16]");
        // 网络流量
        key_val.add("net.if.in[\\\"eth0\\\"]");
        // 网络流量
        key_val.add("net.if.out[\\\"eth0\\\"]");
        // 华为cpu
        key_val.add("system.hw.cpu[0,curfreq]");
        // 系统名称
        key_val.add("system.uname");
        // retuen 列表
        List<String> name_val = new ArrayList<>();
        name_val.add("*Total space*");
        name_val.add("*Used space*");
        name_val.add("*Disk read rate*");
        name_val.add("*Disk write rate*");
        name_val.add("*Memory utilization*");
        /**
         * 参数组装
         */
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("params",new HashMap<String,Object>(){{
                put("output",itemList);
                put("hostids",hostId);
                put("search",new HashMap<String,Object>(){{
                    put("key_",key_val);
                    put("name",name_val);
                }});
                put("searchWildcardsEnabled",true);
                put("searchByAny",true);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String,Object>> resultList = (List<Map<String,Object>>)responseMap.get("result");
        return resultList;
    }


    // 根据主机id获取cpu和内存监控项
    public List<Map<String,Object>> get_cup_and_mem_item_byid(String hostid, String token) {
        List<String> itemList = new ArrayList<>();
        itemList.add("lastvalue");
        itemList.add("key_");
        itemList.add("hostid");
        List<String> key_val = new ArrayList<>();
        key_val.add("vm.memory.utilization");
        key_val.add("vm.memory.util");
        key_val.add("system.cpu.util");
        key_val.add("system.cpu.util[hwEntityCpuUsage.67108873]");
        key_val.add("vm.memory.util[hwEntityMemUsage.67108873]");
        List<String> name_val = new ArrayList<>();
        name_val.add("*Memory utilization*");
        /**
         * 参数组装
         */
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("params",new HashMap<String,Object>(){{
                put("output",itemList);
//                put("search",new HashMap<String,Object>(){{
//                    put("key_",key_val);
//                    put("name",name_val);
//                }});
                put("filter",new HashMap<String,Object>(){{
                    put("key_",key_val);
                }});
                put("hostids",hostid);
//                put("searchWildcardsEnabled",true);
//                put("searchByAny",true);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String,Object>> resultList = (List<Map<String,Object>>)responseMap.get("result");
        return resultList;
    }

    // 根据主机id获取cpu、内存、磁盘监控项
    public Map<String,Object> get_cup_and_mem_disk_item_byid(String hostid, String token) {
//需要返回主机中的itemId和name属性
        String[] items = new String[] {"itemid","name","lastvalue","type"};
        //请求的数据
        String [] data =new String[]{
                "CPU utilization","Available memory in %","vda: Disk utilization","Total swap space", "Space utilization","Total space","Used space",
                "Memory utilization","system.cpu.util[hwEntityCpuUsage.67108873]","vm.memory.util[hwEntityMemUsage.67108873]"
        };
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("searchByAny",true);
                put("output", items);
                put("hostids", hostid);
                put("search", new HashMap<String, Object>(){{
                    put("name", data);
                }});
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        String[] items1 = new String[] {"host"};
        Map<String, Object> par = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", items1);
                put("hostids",hostid);
            }});
        }};
        Map<String, Object> responseMap1 = APIUtils.sendRequest(JSON.toJSONString(par, SerializerFeature.WriteMapNullValue));
        //jsonArray对象进行值的获取
        JSONArray jsonArray=(JSONArray)responseMap1.get("result");
        String hostname= jsonArray.getJSONObject(0).getString("host");
        jsonArray=(JSONArray)responseMap.get("result");
        Map<String,Object> map = new HashMap<>();
        map.put("hostname",hostname);
        List<Map<String, Object>> resultList = (List<Map<String, Object>>)responseMap.get("result");
        long totalSpace = 0L;
        long usedSpace = 0l;
        for (Map<String, Object> stringObjectMap : resultList) {
            String s = (String) stringObjectMap.get("name");
            if(s.contains("Total space"))
            {
                totalSpace+=Long.parseLong((String) stringObjectMap.get("lastvalue"));
            }
            else if(s.contains("Used space"))
            {
                usedSpace+=Long.parseLong((String) stringObjectMap.get("lastvalue"));
            }
            else if (s.contains("cpu") || s.contains("CPU")){
                map.put("cpuUtilization", stringObjectMap.get("lastvalue"));
            }else if (s.contains("memory") || s.contains("Memory")){
                map.put("memUtilization", stringObjectMap.get("lastvalue"));
            }
        }

        if (totalSpace == 0L) {
            map.put("diskUtilization", 0);
        }else {
            map.put("diskUtilization", usedSpace * 1.0 / totalSpace);
        }
        return map;
    }

    // 获取所有内存监控项
    public List<Map<String,Object>> get_mem_item( String token, List<String> hostids) {
        List<String> itemList = new ArrayList<>();
        itemList.add("key_");
        itemList.add("name");
        itemList.add("lastvalue");
        itemList.add("itemid");
        itemList.add("hostid");
        List<String> key_val = new ArrayList<>();
        key_val.add("vm.memory.utilization");
        key_val.add("vm.memory.util");
        key_val.add("vm.memory.util[hwEntityMemUsage.67108873]");
//        List<String> name_val = new ArrayList<>();
//        name_val.add("*Memory utilization*");
//        List<String> type_ = new ArrayList<>();
//        type_.add("15");
//        type_.add("18");
//        type_.add("20");
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("params",new HashMap<String,Object>(){{
                put("output",itemList);
//                put("search",new HashMap<String,Object>(){{
////                    put("key_",key_val);
////                    put("name",name_val);
////                }});
                put("filter",new HashMap<String,Object>(){{
                    put("key_",key_val);
//                    put("type",type_);
                    put("hostid",hostids);
                }});
//                put("searchWildcardsEnabled",true);
//                put("searchByAny",true);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String,Object>> resultList = (List<Map<String,Object>>)responseMap.get("result");
        return resultList;
    }



    //通过hostid获得snmp设备的item信息
    @Override
    public List<Map<String, Object>> get_snmp_item_id(String hostId) {
        final String token = APIUtils.getToken();
        List<String> itemList = new ArrayList<>();
        itemList.add("key_");
        itemList.add("name");
        itemList.add("lastvalue");
        itemList.add("lastclock");
        List<String> key_val = new ArrayList<>();
        key_val.add("system.cpu.util[hwEntityCpuUsage.67108873]");
        key_val.add("vm.memory.util[hwEntityMemUsage.67108873]");
        /**
         * 参数组装
         */
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("params",new HashMap<String,Object>(){{
                put("output",itemList);
                put("hostids",hostId);
                put("search",new HashMap<String,Object>(){{
                    put("key_",key_val);
                }});
                put("searchWildcardsEnabled",true);
                put("searchByAny",true);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String,Object>> resultList = (List<Map<String,Object>>)responseMap.get("result");
        return resultList;
    }

    /**
     * 设置新添加设备更新系统描述时间
     * @param token
     * @param hostid
     */
    @Override
    public void setSystemDescDelayAs2s(String token, String hostid) {
        List<String> output = new ArrayList<>();
        output.add("itemid");
        /**
         * 参数组装
         */
        Map<String, Object> dataMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", output);
                put("hostids", hostid);
                put("search",new HashMap<String,Object>(){{
                    put("key_","system.uname");
                }});
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(dataMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseMap.get("result");
        String itemid = (String) resultList.get(0).get("itemid");

        /**
         * 参数组装
         */
        Map<String, Object> dataMap2 = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.update");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", "extend");
                put("itemid", itemid);
                put("delay", "3s");
            }});
        }};
        Map<String, Object> responseMap2 = APIUtils.sendRequest(JSON.toJSONString(dataMap2, SerializerFeature.WriteMapNullValue));

    }

    /**
     * 重置更新时间
     * @param token
     * @param hostid
     */
    @Override
    public void resetSystemDescDelay(String token, String hostid) {
        List<String> output = new ArrayList<>();
        output.add("itemid");
        /**
         * 参数组装
         */
        Map<String, Object> dataMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", output);
                put("hostids", hostid);
                put("search",new HashMap<String,Object>(){{
                    put("key_","system.uname");
                }});
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(dataMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseMap.get("result");
        String itemid = (String) resultList.get(0).get("itemid");

        /**
         * 参数组装
         */
        Map<String, Object> dataMap2 = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "item.update");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output", "extend");
                put("itemid", itemid);
                put("delay", "1h");
            }});
        }};
        Map<String, Object> responseMap2 = APIUtils.sendRequest(JSON.toJSONString(dataMap2, SerializerFeature.WriteMapNullValue));
    }

    /**
     * 通过HostID获取主机组ID
     * @param hostid
     * @return
     */
    @Override
    public String getInterfaceidBuHostid(String hostid) {
        String token = APIUtils.getToken();
        /**
         * 参数组装
         */
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "hostinterface.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                put("output", "interfaceid");
                put("hostids", hostid);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        JSONArray arr = (JSONArray) responseMap.get("result");
        JSONObject obj = (JSONObject) arr.get(0);
        return obj.get("interfaceid").toString();
    }

    // 获取cpu监控项
    public List<Map<String,Object>> get_cup_item( String token, List<String> hostids) {
        List<String> itemList = new ArrayList<>();
        itemList.add("key_");
        itemList.add("name");
        itemList.add("lastvalue");
        itemList.add("itemid");
        itemList.add("hostid");
        List<String> key_val = new ArrayList<>();
        key_val.add("system.cpu.util");
        key_val.add("system.cpu.util[hwEntityCpuUsage.67108873]");
//        List<String> type_ = new ArrayList<>();
//        type_.add("0");
//        type_.add("4");
//        type_.add("15");
//        type_.add("18");
//        type_.add("20");
        /**
         * 参数组装
         */
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "item.get");
            put("id", 1);
            put("params",new HashMap<String,Object>(){{
                put("output",itemList);
//                put("search",new HashMap<String,Object>(){{
//                    put("key_",key_val);
//                }});
                put("filter",new HashMap<String,Object>(){{
                    put("key_",key_val);
//                    put("type",type_);
                    put("hostid",hostids);
                }});
//                put("searchWildcardsEnabled",true);
//                put("searchByAny",true);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String,Object>> resultList = (List<Map<String,Object>>)responseMap.get("result");
        return resultList;
    }


    /**
     * @Description 参数：模板id、监控项名称name、监控项键值key
     * @date 2021/5/29 16:23
     */
    public Map<String, Object> createLogItemToTemplate(String templatesid,String key,String name){
        String token = APIUtils.getToken();
        // 创建磁盘监控项
        Map<String, Object> writeItemMap = new HashMap<String, Object>(){{
            put("auth",token);
            put("jsonrpc", "2.0");
            put("method", "item.create");
            put("id", 1);
            put("params", new HashMap<String,Object>(){{
                put("hostid",templatesid);
                put("delay","1m");
                put("key_",key);
                put("name",name);
                put("type",7);
                put("value_type",2);
                put("description","系统日志监控。");
                put("history","90d");
                put("trends","365d");
            }});
        }};
        return APIUtils.sendRequest(JSON.toJSONString(writeItemMap, SerializerFeature.WriteMapNullValue));
    }
}
